<template>
<div class="update-gender">
<van-picker
  title="设置性别"
  :default-index="gender"
  :columns="columns"
  @cancel="$emit('close')"
  @confirm="onConfirm"
  @change="onChange"
/>
</div>
</template>

<script>
import { updateUserProfile } from '@/api/user'
import { Toast } from 'vant'
import { ref } from 'vue'
export default {
  name: 'UpdateGender',
  props: {
    gender: {
      type: Number,
      required: true
    }
  },
  setup (props, context) {
    const columns = [
      { text: '男' },
      { text: '女' }
    ]
    const localGender = ref(props.gender)// 0男1女
    async function onConfirm () {
      Toast.loading({
        message: '保存中...',
        forbidClick: true, // 禁用背景点击
        duration: 0// 持续展示，直到下个Toast出现
      })
      try {
        await updateUserProfile({
          gender: localGender.value
        })
        context.emit('confirmSuccess', localGender.value)
        Toast.success('更新成功')
      } catch (err) {
        if (err.response && err.response.status === 401) {
          Toast.fail('请重新登录')
        } else {
          Toast.fail('操作失败')
        }
      }
    }
    function onChange (picker, value) { // 滑动触发
      localGender.value = value
    }
    return {
      columns,
      localGender,
      onConfirm,
      onChange
    }
  }
}
</script>

<style>

</style>
